<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <searchrevealing>
                <el-tabs v-model="activeTab" @tab-change="tabChange">
                    <el-tab-pane label="核价初审" name="HJCS" />
                    <el-tab-pane label="核价复审" name="HJFS" />
                    <el-tab-pane label="无合同审批" name="WHTSP" />
                    <el-tab-pane label="入库审批" name="RKSP" />
                    <el-tab-pane label="变价审批" name="BJSP" />
                    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="104px">
                        <el-form-item label="商品名称" prop="styleName">
                            <el-input v-model="queryParams.styleName" placeholder="请输入商品名称" clearable
                                style="width: 220px" @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="审批状态" prop="status">
                            <el-select style="width: 220px" v-model="queryParams.status" placeholder="请选择" filterable
                                clearable>
                                <el-option v-for="item in examineList" :key="item.value" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="`${activeTab === 'RKSP' ? '初次' : ''}提交日期`" prop="pricingTime">
                            <el-date-picker value-format="YYYY-MM-DD" v-model="pricingTime" type="daterange"
                                @change="pricingPickerChange" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                                style="width: 220px" />
                        </el-form-item>
                    </el-form>
                    <div class="form_button">
                        <el-button type="primary" @click="handleQuery" :loading="loading">查询</el-button>
                        <el-button @click="resetQuery" :loading="loading">重置</el-button>
                    </div>
                </el-tabs>
            </searchrevealing>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"
                        :name="activeTab == 'HJCS' ? '审批中心核价初审' : activeTab == 'HJFS' ? '审批中心核价复审' : activeTab == 'WHTSP' ? '审批中心无合同审批' : activeTab == 'RKSP' ? '审批中心入库审批' : '审批中心变价审批'"
                        @updateColumn="getColmun"></right-toolbar>
                </el-row>
            </template>
            <el-table v-loading="loading" row-key="id" :data="tableData" border @header-dragend="dragEnd">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column v-for="(item, index) in commodityManage" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50"
                            :height="50" />
                        <div v-if="item.prop == 'hmMechanismsList'">
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[0] ||
                                null,
                                '一') }}
                            </div>
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[1] ||
                                null,
                                '二') }}
                            </div>
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[2] ||
                                null,
                                '三') }}
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right" width="200">
                    <template #default="scope">
                        <el-button link size="small" type="primary"
                            @click="handleInfo(scope.row, '查看详情')">查看详情</el-button>
                        <el-button
                            v-if="scope.row.auditStatus != 18 && scope.row.auditStatus != 19 && scope.row.auditStatus != 20 && scope.row.auditStatus != 21"
                            link size="small" type="primary" @click="handleInfo(scope.row, '变更主播')">变更主播</el-button>
                        <el-button
                            v-if="((scope.row.auditStatus == 8 || scope.row.auditStatus == 9 || scope.row.auditStatus == 10) && activeTab == 'HJCS') || (scope.row.auditStatus == 12 && activeTab == 'HJFS') || (scope.row.auditStatus == 17 && activeTab == 'RKSP')"
                            link size="small" type="primary" @click="handleInfo(scope.row, '编辑')">编辑</el-button>
                        <el-button
                            v-if="activeTab == 'HJCS' && (scope.row.auditStatus == 8 || scope.row.auditStatus == 9 || scope.row.auditStatus == 10)"
                            link size="small" type="primary" @click="handleInfo(scope.row, '发起初审')">发起初审</el-button>
                        <el-button v-if="activeTab == 'HJFS' && (scope.row.auditStatus == 12)" link size="small"
                            type="primary" @click="handleInfo(scope.row, '发起复审')">发起复审</el-button>
                        <el-button v-if="activeTab == 'HJFS' && scope.row.auditStatus == 13" link size="small"
                            type="primary" @click="handleInfo(scope.row, '无合同审批')">无合同审批</el-button>
                        <el-button
                            v-if="(activeTab == 'HJFS' && scope.row.auditStatus == 15) || (activeTab == 'WHTSP' && scope.row.auditStatus == 15)"
                            link size="small" type="primary" @click="handleInfo(scope.row, '发起入库')">发起入库</el-button>
                        <el-button v-if="activeTab == 'RKSP' && scope.row.auditStatus == 17" link size="small"
                            type="primary" @click="handleInfo(scope.row, '重新入库')">重新入库</el-button>

                        <el-button
                            v-if="(activeTab == 'RKSP' && (scope.row.auditStatus == 18 || scope.row.auditStatus == 20 || scope.row.auditStatus == 21)) || (activeTab == 'BJSP' && (scope.row.auditStatus == 20 || scope.row.auditStatus == 21))"
                            link size="small" type="primary" @click="handleInfo(scope.row, '变价审核')">变价审核</el-button>
                        <!-- <el-button link size="small" type="primary"
                            @click="handleInfo(scope.row, '撤回')">撤回</el-button> -->


                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableTotal > 0" :total="tableTotal" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" />
        </el-card>
        <el-drawer v-model="isAddDrawer" :title="AddFormTitle" direction="rtl" size="70%" :before-close="handleClose"
            :close-on-click-modal="false">
            <commodityHistorydetails v-if="isAddDrawer" @onSubmit="AddFormSubmit" :title="AddFormTitle"
                :AddFormId="AddFormId" :disabledName="disabledName" :activeTab="activeTab" />
        </el-drawer>
        <el-drawer v-model="anchorSelectionVisible" title="主播选品" direction="rtl" size="30%"
            :before-close="anchorSelectionHandleClose" :close-on-click-modal="false">
            <anchorSelection :id="productId" v-if="anchorSelectionVisible" @close="anchorSelectionHandleClose"
                @submit="anchorSelectionHandleChange" :isChange="isChangeList" @onChangeSubmit="onChangeSubmit">
            </anchorSelection>
        </el-drawer>
        <!-- 送审 -->
        <qualificationsDialog :qualificationsDialogVisible="qualificationsFlag" :id="productId"
            @close="qualificationsFlag = false" @submit="qualificationsFlagSubmit"></qualificationsDialog>
        <!-- 无合同审批 -->
        <noContractApprovalDialog :noContractApprovalDialogVisible="noContractApprovalFlag" :id="productId"
            @close="noContractApprovalFlag = false" @submit="noContractApprovalSubmit"></noContractApprovalDialog>
        <!-- 变价审核 -->
        <el-drawer v-model="mechanismPriceChangeVisible" title="变价审批" direction="rtl" size="50%"
            :before-close="mechanismPriceChangeHandleClose" :close-on-click-modal="false">
            <mechanismPriceChange v-if="mechanismPriceChangeVisible" @close="mechanismPriceChangeHandleClose"
                @submit="mechanismPriceChangeHandleChange" :isChangeList="mechanismPriceChangeList">
            </mechanismPriceChange>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance() as any;
import { getPriceFirstListInventPe, getPriceSecondListInventPe, getContractFirstListInventPe, getStockListInventPe, getStockPriceInventPe } from '@/api/group/productOutbound/index'
import { editSevens, editTen, reAuditSecond, submitAudit, againStock } from '@/api/group/product/index'
import commodityHistorydetails from './components/look.vue'
import anchorSelection from '@/views/group/investDepartment/commodityManage/components/anchorSelection.vue'
import useUserStore from '@/store/modules/user';
import { handleEditPermission } from '@/utils/auditStatusFilter'
import noContractApprovalDialog from '@/views/group/investDepartment/commodityManage/components/noContractApprovalDialog.vue'
import mechanismPriceChange from '@/views/group/investDepartment/commodityManage/components/mechanismPriceChange.vue'
import qualificationsDialog from '@/views/group/investDepartment/commodityManage/components/qualificationsDialog.vue'
import Qs from "qs";
const commodityManage = ref()
const columnData = ref()
const activeTab = ref('HJCS');
const queryFormRef = ref();
const showSearch = ref(true);
const loading = ref(false);

// 主播选品显隐
const anchorSelectionVisible = ref(false)
/** 退出主播选品二次确认 */
const anchorSelectionHandleClose = async () => {
    await proxy?.$modal.confirm('是否退出当前编辑页面，已编辑的信息将被清空');
    anchorSelectionVisible.value = false
}
// 弹窗操作商品id
const productId = ref()
/** 选择主播 */
const anchorSelectionHandleChange = async () => {
    proxy?.$modal.msgSuccess('选择主播成功');
    anchorSelectionVisible.value = false
    await getList()
}
// 变更主播数据
const isChangeList = ref()
/** 更改主播 */
const onChangeSubmit = async () => {
    proxy?.$modal.msgSuccess('主播更改成功');
    isChangeList.value = undefined
    anchorSelectionVisible.value = false
    await getList()
}

// 发起送审显隐
const qualificationsFlag = ref(false)
/** 送审成功 */
const qualificationsFlagSubmit = async () => {
    qualificationsFlag.value = false
    await getList()
}

const isAddDrawer = ref(false)
const AddFormTitle = ref('')
const AddFormId = ref('')
const disabledName = ref('')
// 商品提交回调函数
const AddFormSubmit = (type: string | undefined, productsId?: string) => {
    isAddDrawer.value = false
    if (type) {
        handleInfo({ id: AddFormId.value, productsId: productsId }, type == 'HJCS' ? '发起初审' : type == 'HJFS' ? '发起复审' : type == 'RKSP' ? '发起入库' : '')
    }
    getList()
}
// 弹框关闭
const handleClose = async () => {
    if (AddFormTitle.value == '查看详情') {
        isAddDrawer.value = false
    } else {
        await proxy?.$modal.confirm('是否退出当前编辑页面，已编辑的商品信息将被清空');
        isAddDrawer.value = false
    }
}

// 无合同审批显隐
const noContractApprovalFlag = ref(false)

/** 无合同审批成功 */
const noContractApprovalSubmit = async () => {
    noContractApprovalFlag.value = false
    await getList()
}

// 变价审批显隐
const mechanismPriceChangeVisible = ref(false)
// 变价审核数据
const mechanismPriceChangeList = ref()
/** 变价审核二次确认 */
const mechanismPriceChangeHandleClose = async () => {
    await proxy?.$modal.confirm('是否退出当前编辑页面，已编辑的信息将被清空');
    mechanismPriceChangeVisible.value = false
}
/** 变价审核关闭 */
const mechanismPriceChangeHandleChange = async () => {
    proxy?.$modal.msgSuccess('变价审核提交成功');
    mechanismPriceChangeVisible.value = false
    await getList()
}

// 提交时间
const pricingTime = ref()
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    type: 0,
    status: undefined,
    startTime: '',
    endTime: '',
    styleName: '',
})
const tableData = ref([])
const tableTotal = ref(0)
// 审批状态
const examineList = ref([
    { label: '审批中', value: '0' },
    { label: '已通过', value: '2' },
    { label: '已驳回', value: '1' },
])
// 查询列表数据
const getList = async () => {
    try {
        loading.value = true
        let res: any = null
        if (activeTab.value === 'HJCS') {
            res = await getPriceFirstListInventPe(queryParams.value)
        } else if (activeTab.value === 'HJFS') {
            res = await getPriceSecondListInventPe(queryParams.value)
        } else if (activeTab.value === 'WHTSP') {
            res = await getContractFirstListInventPe(queryParams.value)
        } else if (activeTab.value === 'RKSP') {
            res = await getStockListInventPe(queryParams.value)
        } else if (activeTab.value === 'BJSP') {
            res = await getStockPriceInventPe(queryParams.value)
        }
        tableData.value = res.rows || []
        tableTotal.value = res.total || 0
        loading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
}
/** 提交时间 */
const pricingPickerChange = (val: string[]) => {
    if (val) {
        queryParams.value.startTime = val[0]
        queryParams.value.endTime = val[1]
    } else {
        queryParams.value.startTime = ''
        queryParams.value.endTime = ''
    }
}
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}
/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    pricingTime.value = undefined
    queryParams.value.startTime = ''
    queryParams.value.endTime = ''
    handleQuery();
};
// 直播机制反显
const computedMechanism = (row: any, numbers: string) => {
    if (row) {
        const price = row.price ? row.price : '-'
        const commission = row.commission ? row.commission + '%' : '-'
        const brokerage = row.brokerage ? row.brokerage + '%' : '-'
        const liveStreamingMechanism = row.liveStreamingMechanism ? row.liveStreamingMechanism : '-'
        const costPrice = row.costPrice ? row.costPrice : '-'
        if (row.cooperationMode) {
            if (row.cooperationMode == '分佣') {
                return '机制' + numbers + ': ' + '售价:' + price + ' 佣金:' + commission + ' 补充佣金:' + brokerage + ' 机制:' + liveStreamingMechanism + ' 成本:' + costPrice
            } else {
                return '机制' + numbers + ': ' + '成本:' + costPrice + ' 机制:' + liveStreamingMechanism
            }
        }
    }
}
/** 查看商品详情 */
const handleInfo = (row: any, title: string) => {
    if (title === '查看详情') {
        isAddDrawer.value = true;
        AddFormTitle.value = title
        AddFormId.value = row.id
        disabledName.value = ''
    } else if (title == '编辑') {
        isAddDrawer.value = true;
        AddFormTitle.value = title
        AddFormId.value = row.id
        switch (handleEditPermission(row.auditStatus)) {
            // 都不可编辑
            case '0':
                disabledName.value = ''
                break;
            // 都可编辑
            case '1':
                disabledName.value = 'all'
                break;
            // 编辑商品信息，除了机制
            case '3':
                disabledName.value = 'noMechanism'
                break;
            // 只可编辑机制 规格/材质 卖点 商品图 对接群名
            case '4':
                disabledName.value = 'rejectStatus'
                break;
            // 只可编辑规格/材质 卖点 商品图 对接群名
            case '5':
                disabledName.value = 'alwaysEdit'
                break;
            default:
                break;
        }
    } else if (title === '变更主播') {
        productId.value = row.productsId
        isChangeList.value = {
            coreName: row.coreName,
            coreId: row.coreDeptId,
            liveType: row.liveType
        }
        anchorSelectionVisible.value = true
    } else if (title === '发起初审') {
        const { deptName } = useUserStore();
        if (deptName != '食品部' && deptName != '鞋帽部' && deptName != '百货部' && deptName != '酒茶部' && deptName != '箱包部' && deptName != '服装部') {
            qualificationsFlag.value = true
            productId.value = [row.id]
        } else {
            ElMessageBox.confirm('是否确认发起核价初审审批？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                callback: async (action: any) => {
                    if (action == 'confirm') {
                        await editSevens({ ids: [row.id] });
                        proxy?.$modal.msgSuccess('商品送审成功');
                        await getList()
                    }
                },
            })
        }
    } else if (title === '发起复审') {
        ElMessageBox.confirm('是否确认重新发起核价复审审批？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            callback: async (action: any) => {
                if (action == 'confirm') {
                    await reAuditSecond({ id: row.id });
                    proxy?.$modal.msgSuccess('商品送审成功');
                    await getList()
                }
            },
        })
    } else if (title === '无合同审批') {
        noContractApprovalFlag.value = true
        productId.value = row.id
    } else if (title === '发起入库') {
        // 无合同驳回时
        if (row.auditStatus == 14) {
            if (row.sellStatus == "已签署") {
                ElMessageBox.confirm('是否确认发起入库审批？', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    callback: async (action: any) => {
                        if (action == 'confirm') {
                            await submitAudit({ productId: row.productsId, type: 'PRODUCT_STOCK_AUDIT' })
                            proxy?.$modal.msgSuccess('产品入库中');
                            await getList()
                        }
                    },
                })
            } else {
                proxy?.$modal.msgError('无法入库,当前商品暂无供销合同，请关注供销合同上传或无合同审批进展...');
            }
        } else {
            ElMessageBox.confirm('是否确认发起入库审批？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                callback: async (action: any) => {
                    if (action == 'confirm') {
                        await editTen(Qs.stringify({ ids: [row.productsId] }, { arrayFormat: 'repeat' }));
                        proxy?.$modal.msgSuccess('产品入库中');
                        await getList()
                    }
                },
            })
        }
    } else if (title === '重新入库') {
        ElMessageBox.confirm('是否确认重新发起入库审批？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            callback: async (action: any) => {
                if (action == 'confirm') {
                    await againStock({ id: row.productsId });
                    proxy?.$modal.msgSuccess('产品重新入库中');
                    await getList()
                }
            },
        })
    } else if (title === '变价审核') {
        mechanismPriceChangeVisible.value = true
        mechanismPriceChangeList.value = {
            id: row.productsId,
            styleName: row.styleName,
            specs: row.specs,
            sellingPoints: row.sellingPoints,
            productImage: row.productImage,
            tax: row.tax,
            hmMechanismsList: row.hmMechanismsList
        }
    }
};

/** 获取colmun */
const getColmun = async () => {
    let columnDatas = null
    if (activeTab.value === 'HJCS') {
        columnDatas = await proxy?.useColumn('审批中心核价初审')
    } else if (activeTab.value === 'HJFS') {
        columnDatas = await proxy?.useColumn('审批中心核价复审')
    } else if (activeTab.value === 'WHTSP') {
        columnDatas = await proxy?.useColumn('审批中心无合同审批')
    } else if (activeTab.value === 'RKSP') {
        columnDatas = await proxy?.useColumn('审批中心入库审批')
    } else if (activeTab.value === 'BJSP') {
        columnDatas = await proxy?.useColumn('审批中心变价审批')
    }
    commodityManage.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}
const tabChange = async () => {
    queryFormRef.value?.resetFields();
    queryParams.value.pageNum = 1;
    pricingTime.value = undefined
    queryParams.value.startTime = ''
    queryParams.value.endTime = ''
    await getColmun()
    await getList()
}
onMounted(async () => {
    await getColmun()
    await getList()
})
</script>

<style lang="scss" scoped>
.form_button {
    display: flex;
    justify-content: flex-end;
}
</style>